package com.ctsi.auth.integration;

import com.ctsi.auth.event.LoginInfoResouce;
import com.ctsi.auth.event.UserLoginBeforeEvent;
import com.ctsi.commons.util.id.UUIDGenerator;
import com.ctsi.commons.util.request.ParameterRequestWrapper;
import com.ctsi.commons.util.request.UtilHttp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.core.annotation.Order;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.OrRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author zhangjw
 * @className UserLoginRecordFilter
 * @description 用于记录用户登陆地址
 * @date 2019/3/2 10:37
 **/
@Component
@Order(Integer.MIN_VALUE)
public class UserLoginRecordFilter extends GenericFilterBean implements ApplicationContextAware, ApplicationEventPublisherAware {
    private static final Logger logger = LoggerFactory.getLogger(UserLoginRecordFilter.class);

    private static final String FILTER_APPLIED = "__spring_security_demoFilter_filterApplied";

    /**
     * 要拦截的登陆地址
     */
    private static final String OAUTH_TOKEN_URL = "/oauth/token";

    private ApplicationContext applicationContext;

    private ApplicationEventPublisher applicationEventPublisher;

    private RequestMatcher requestMatcher;

    public UserLoginRecordFilter(){
        this.requestMatcher = new OrRequestMatcher(
                new AntPathRequestMatcher(OAUTH_TOKEN_URL, "GET"),
                new AntPathRequestMatcher(OAUTH_TOKEN_URL, "POST")
        );
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        if (servletRequest.getAttribute(FILTER_APPLIED) != null) {
            filterChain.doFilter(servletRequest, servletResponse);
            return ;
        }
        servletRequest.setAttribute(FILTER_APPLIED,true);
        if(requestMatcher.matches(request)) {
            /**
             * 构造新得request
             */
            ParameterRequestWrapper wrapper = new ParameterRequestWrapper(request);
            LoginInfoResouce resouce = new LoginInfoResouce();
            String id = UUIDGenerator.getId();
            wrapper.addParameter("requestId",id);
            resouce.setId(id);
            String clientIp = UtilHttp.getIpAddr(request);
            resouce.setClientIp(clientIp);
            resouce.setLoginName(request.getParameter("username"));
            String type = request.getParameter("auth_type");
            if ("app".equalsIgnoreCase(type)) {
                resouce.setDeviceName("APP");
            } else {
                resouce.setDeviceName("PC");
            }
            applicationEventPublisher.publishEvent(new UserLoginBeforeEvent(resouce));
            filterChain.doFilter(wrapper,response);

        } else {
            filterChain.doFilter(request,response);
        }
    }


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    /**
     * Set the ApplicationEventPublisher that this object runs in.
     * <p>Invoked after population of normal bean properties but before an init
     * callback like InitializingBean's afterPropertiesSet or a custom init-method.
     * Invoked before ApplicationContextAware's setApplicationContext.
     *
     * @param applicationEventPublisher event publisher to be used by this object
     */
    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        this.applicationEventPublisher = applicationEventPublisher;
    }
}
